import pymongo
import docx,jieba
from pymongo import MongoClient as MC


class Mongo(object):
    def __init__(self):
        client = MC('localhost',27017)
        db = client.wordsdb
        self.words = db.words

    def add_date(self):
        file = docx.Document('word.docx')
        print("段落数："+str(len(file.paragraphs)))
        m=1
        for i in range(len(file.paragraphs)-1):
            if str(file.paragraphs[i].text).strip().isdigit():
                continue
            else:
                str1=file.paragraphs[i].text.strip()
                lis1=str1.split(' ')
                str1=lis1[len(lis1)-1]
                str2 =file.paragraphs[i+1].text.strip()
                lis2=str2.split(' ')
                str2 =lis2[len(lis2)-1]
                if m%2!=0:
                    post={"key":str1,"value":str2}
                    self.words.insert(post)
                else:
                    pass
                m+=1

    def get_data(self,question):
        self.words.create_index([('key',1),('value',1)])
        results = self.words.find()
        res=[]
        for item in results:
            cut = jieba.cut(item['key'])
            cut = ','.join(cut)
            if question in cut:
                res.append(item['key'])
        if len(res)==0:
            print('查询不到')
            exit()
        else:
            return res

    def main(self):
        mongo=Mongo()
        li={}
        txt = input('输入查询关键字：').strip()
        res = mongo.get_data(txt)
        for i,j in enumerate(res,1):
            print(i,j)
            li.setdefault(i,j)
        num = int(input('输入你的问题编号：').strip())
        str0=li[num]
        rest=self.words.find({'key':str0},{'value':1})
        for i in rest:
            print(i['value'])


if __name__ == '__main__':
    mongo=Mongo()
    # mongo.add_date()
    mongo.main()







# str1="问题:",file.paragraphs[i].text.replace(' ','')[1:]
# str2 = "答案:", file.paragraphs[i+1].text.replace(' ', '')[1:]